import configparser
from application import settings


class IniConfigSerializer:
    """
    ini 配置文件序列化
    """

    def __init__(self, file):
        self.file = file
        # 创建管理对象
        self.conf = configparser.ConfigParser()
        # 读ini文件
        self.conf.read(file, encoding="utf-8")

    def get_configs(self) -> dict:
        data = {}
        for section in self.conf.sections():
            item = {}
            for option in self.conf.options(section):
                item[option] = self.conf.get(section, option)
            data[section] = item
        return data

    def update_config(self, data: dict) -> bool:
        for k, v in data.items():
            for section in self.conf.sections():
                if self.conf.has_option(section, k):
                    self.conf.set(section, k, str(v))
                    continue
        self.save()
        return True

    def set_section_item(self, section, key, value):
        """
        get value  from path/xxx.ini  [section]  key=value
        :param section:
        :param key:
        :param value:
        :return:
        """
        if not self.has_section(section):
            print(f"{section}节点不存在，无法设置数据")
            return False
        self.conf.set(section, key, value)
        return True

    def create_section(self, section, data: dict):
        """
        创建节点，如果存在则覆盖
        :param section:
        :param data:
        :return:
        """
        if self.has_section(section):
            print(f"{section}节点已经存在，已覆盖")
        else:
            print(f"成功创建节点，{section}")
            self.conf.add_section(section)
        for key, value in data.items():
            self.conf.set(section, key, value)
        self.save()

    def has_section(self, section):
        """
        判断节点是否存在
        :param section: 节点名称
        :return:
        """
        return self.conf.has_section(section)

    def delete_section(self, section):
        """
        判断节点是否存在
        :param section: 节点名称
        :return:
        """
        if self.has_section(section):
            self.conf.remove_section(section)
        self.save()
        return True

    def save(self):
        """
        保存到文件中
        :return:
        """
        with open(self.file, "w") as f:
            self.conf.write(f)
        settings.SQLALCHEMY_DATABASE_URL = self.get_configs()


if __name__ == '__main__':
    import os
    from application.settings import BASE_DIR
    DATABASE_CONFIG_FILE = os.path.join(BASE_DIR, "application", "conf", "databases.ini")
    ini = IniConfigSerializer(DATABASE_CONFIG_FILE)
    # datas = ini.get_configs()
    # print(datas)
    data = {
        "id": "7",
        "type": "mysql"
    }
    ini.create_section("5-test1", data)



